package org.jeecg.modules.user.cycling.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.MemberAPI;
import org.jeecg.common.api.dto.MemberDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.dto.device.SwitchLockReq;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.staffUser.entity.LoginRes;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.param.staffUser.mapper.StaffMapper;
import org.jeecg.modules.param.station.service.IBikeStationHeartbeatService;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.user.cycling.entity.PileReq;
import org.jeecg.modules.user.cycling.service.CyclingService;
import org.jeecg.modules.util.CommonUtil;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.YueYueNiaoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.math.BigDecimal;

/**
 * @Description: bike_pile
 * @Author: jeecg-boot
 * @Date:   2021-05-19
 * @Version: V1.0
 */
@Service
public class CyclingServiceImpl implements CyclingService {

    @Autowired
    private MemberAPI memberAPI;
    @Resource
    private BikePileMapper bikePileMapper;
    @Resource
    private BikeVehicleMapper bikeVehicleMapper;
    @Autowired
    private BikeVehicleOrderMapper orderMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private BikeStationMapper bikeStationMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IBikeStationHeartbeatService bikeStationHeartbeatService;
    @Transient
    @Override
    public BikeResult getCycling(PileReq pileReq, HttpServletRequest request) {
        // 1:校验token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);

        // 2：校验扫码编号
        if (StringUtils.isEmpty(pileReq.getPileCode()) || pileReq.getPileCode().length()!=11){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        String stationCode = pileReq.getPileCode().substring(0, 5);
        String pileCode = pileReq.getPileCode().substring(5,7);
        String checkCode = pileReq.getPileCode().substring(7,11);

        // 3: 网点校验
        BikeStation bikeStation = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (bikeStation==null){
            return BikeResult.error("0","无效的网点编号",null);
        }
        if (bikeStation.getIsRegister().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","网点未注册，请更换网点",null);
        }
        if (bikeStation.getStatus().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","网点未启用，请更换网点",null);
        }
        //3.1：网点跳包校验  抱歉！当前网点，电量不足，暂时无法借车。
        boolean b = bikeStationHeartbeatService.stationIsLowBattery(bikeStation.getId());
        if (b){
            return BikeResult.error("0","抱歉，当前网点电量不足，暂时无法借车",null);
        }
        // 4：车桩校验
        QueryWrapper<BikePile> pileWrapper = new QueryWrapper<>();
        pileWrapper.eq("code", CommonUtil.switchPileCode(pileCode));
        pileWrapper.eq("station_id", bikeStation.getId());
        pileWrapper.eq("check_code", checkCode);
        BikePile bikePile = bikePileMapper.selectOne(pileWrapper);
        if (bikePile==null){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        if (bikePile.getStatus().equals(BikeConstant.y_n_no)){
            return BikeResult.error("0","车桩未启用，请更换车桩",null);
        }
        if (bikePile.getIsLock().equals(BikeConstant.y_n_yes)){
            return BikeResult.error("0","车桩被锁定，请更换车桩",null);
        }

        // 5.用户端扫码  2.员工端扫码
        SwitchLockReq switchLockReq = new SwitchLockReq();
        if (pileReq.getType() == 1){
            // 网点锁定状态下，普通用户车辆只可以还不可以借取；
            if (bikeStation.getIsLock().equals(BikeConstant.y_n_yes)){
                return BikeResult.error("0",bikeStation.getLockCause(),null);
            }
            // 6:车辆校验
            QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
            wrapper.eq("pile_id", bikePile.getId());
            BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(wrapper);
            if (bikeVehicle==null){
                return BikeResult.error("0","车桩无车，请更换车桩",null);
            }
            if (bikeVehicle.getStatus().equals(BikeConstant.bike_status_ride)){
                return BikeResult.error("0","车辆异常，请更换车桩",null);
            }
            if (bikeVehicle.getIsRegister().equals(BikeConstant.y_n_no)){
                return BikeResult.error("0","车辆异常，请更换车桩",null);
            }
            // app用户扫码 用户校验
            MemberDTO member = memberAPI.getMember(username);
            if (member.getBalance().compareTo(new BigDecimal(0))==-1){
                return BikeResult.error("0","你已欠费，请充值后使用",null);
            }
            if (!member.getStatus().equals(BikeConstant.member_status_normal)){
                return BikeResult.error("0","账号状态异常，请联系客服电话",null);
            }
            if (member.getIsCertification().equals(BikeConstant.y_n_no)){
                return BikeResult.error("0","请先实名认证",null);
            }
            // 校验成年
            String ageJudge = YueYueNiaoUtils.idcardNumberToAge(member.getIdCard());
            if (!ageJudge.equals(BikeConstant.y_n_yes)){
                return BikeResult.error("0",ageJudge,null);
            }

            // 验证是否存在未支付订单
            BikeVehicleOrder bikeVehicleOrder = orderMapper.selectOne(new QueryWrapper<BikeVehicleOrder>().eq("pick_user", member.getId()).eq("is_pay", "0"));
            if (bikeVehicleOrder!=null){
                return BikeResult.error("0","上一笔订单未支付",null);
            }

            // 下发开锁指令用户信息
            switchLockReq.setUserCode(member.getId());
            switchLockReq.setUserType(1);
        } else {
            // 7:员工用户扫码 用户校验
            LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LoginRes::getUsername,username);
            LoginRes sysUser = staffMapper.selectOne(queryWrapper);
            if(sysUser == null){
                return BikeResult.error("0","用户信息不存在，请联系管理员",null);
            }
            if(sysUser.getStatus() == 2){
                return BikeResult.error("0","当前用户为冻结状态，无法借车",null);
            }

            // 下发开锁指令用户信息
            switchLockReq.setUserCode(sysUser.getId());
            switchLockReq.setUserType(2);
        }

        // 8：下发开锁指令
        switchLockReq.setStationCode(stationCode);
        switchLockReq.setPileCode(pileCode);
        //1 开锁 0关锁
        switchLockReq.setIsLock(1);
        Result<?> result = deviceService.switchLock(switchLockReq);
        if (result.getCode() == 200){
            return BikeResult.ok("1","已发送开锁指令",null);
        }else {
            return BikeResult.error("0",result.getMessage(),null);
        }
    }

    @Override
    public BikeResult checkPileCode(PileReq pileReq, HttpServletRequest request) {
        // 1:校验token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        // 2：校验扫码编号
        if (StringUtils.isEmpty(pileReq.getPileCode()) || pileReq.getPileCode().length()!=11){
            return BikeResult.error("0","无效的车桩编号",null);
        }
        String stationCode = pileReq.getPileCode().substring(0, 5);
        String pileCode = pileReq.getPileCode().substring(5,7);
        String checkCode = pileReq.getPileCode().substring(7,11);
        // 3: 网点校验
        BikeStation bikeStation = bikeStationMapper.selectOne(new QueryWrapper<BikeStation>().eq("code", stationCode));
        if (bikeStation==null){
            return BikeResult.error("0","无效的网点编号",null);
        }
        // 4：车桩校验
        QueryWrapper<BikePile> pileWrapper = new QueryWrapper<>();
        pileWrapper.eq("code", CommonUtil.switchPileCode(pileCode));
        pileWrapper.eq("station_id", bikeStation.getId());
        pileWrapper.eq("check_code", checkCode);
        BikePile bikePile = bikePileMapper.selectOne(pileWrapper);
        if (bikePile==null||!bikePile.getCheckCode().equals(checkCode)){
            return BikeResult.error("0","无效的车桩编号",null);
        }

        if (pileReq.getType()!=null){
            if (pileReq.getType() == 1){
                // app用户扫码 用户校验
                MemberDTO member = memberAPI.getMember(username);
                if (member.getIsCertification().equals(BikeConstant.y_n_no)){
                    return BikeResult.error("0","请先实名认证",null);
                }
                if (member.getStatus().equals(BikeConstant.member_status_abnormal)){
                    return BikeResult.error("0","账号状态异常，请联系客服电话",null);
                }else if (member.getStatus().equals(BikeConstant.member_status_blacklist)){
                    return BikeResult.error("0","已被拉入黑名单，请联系客服电话",null);
                }else if (member.getStatus().equals(BikeConstant.member_status_logout)){
                    return BikeResult.error("0","账号已销户，请联系客服电话",null);
                }
                if (member.getBalance().compareTo(new BigDecimal(0))==-1){
                    return BikeResult.error("0","你已欠费，请充值后使用",null);
                }
                // 网点锁定状态下，普通用户车辆只可以还不可以借取；
                if (bikeStation.getIsLock().equals(BikeConstant.y_n_yes)){
                    return BikeResult.error("0",bikeStation.getLockCause(),null);
                }
                // 6:车辆校验
                QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
                wrapper.eq("pile_id", bikePile.getId());
                BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(wrapper);
                if (bikeVehicle==null){
                    return BikeResult.error("0","车桩无车，请更换车桩",null);
                }
                if (bikeVehicle.getStatus().equals(BikeConstant.bike_status_ride)){
                    return BikeResult.error("0","车辆异常，请更换车桩",null);
                }
                if (bikeVehicle.getIsRegister().equals(BikeConstant.y_n_no)){
                    return BikeResult.error("0","车辆异常，请更换车桩",null);
                }
                // 校验成年
                String ageJudge = YueYueNiaoUtils.idcardNumberToAge(member.getIdCard());
                if (!ageJudge.equals(BikeConstant.y_n_yes)){
                    return BikeResult.error("0",ageJudge,null);
                }
                // 验证是否存在未支付订单
                BikeVehicleOrder bikeVehicleOrder = orderMapper.selectOne(new QueryWrapper<BikeVehicleOrder>().eq("pick_user", member.getId()).eq("is_pay", "0"));
                if (bikeVehicleOrder!=null){
                    return BikeResult.error("0","上一笔订单未支付",null);
                }
            } else {
                // 7:员工用户扫码 用户校验
                LambdaQueryWrapper<LoginRes> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LoginRes::getUsername,username);
                LoginRes sysUser = staffMapper.selectOne(queryWrapper);
                if(sysUser == null){
                    return BikeResult.error("0","用户信息不存在，请联系管理员",null);
                }
                if(sysUser.getStatus() == 2){
                    return BikeResult.error("0","当前用户为冻结状态，无法借车",null);
                }

            }
        }else {
            if (bikeStation.getIsRegister().equals(BikeConstant.y_n_no)){
                return BikeResult.error("0","网点未注册，请更换网点",null);
            }
            if (bikeStation.getStatus().equals(BikeConstant.y_n_no)){
                return BikeResult.error("0","网点未启用，请更换网点",null);
            }

            if (bikePile.getStatus().equals(BikeConstant.y_n_no)) {
                return BikeResult.error("0", "车桩未启用，请更换车桩", null);
            }
            // 6:车辆校验
            QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
            wrapper.eq("pile_id", bikePile.getId());
            BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(wrapper);
            if (bikeVehicle == null) {
                return BikeResult.error("0", "车桩无车，请更换车桩", null);
            }
            if (bikeVehicle.getStatus().equals(BikeConstant.bike_status_ride)) {
                return BikeResult.error("0", "车辆异常，请更换车桩", null);
            }
            if (bikeVehicle.getIsRegister().equals(BikeConstant.y_n_no)) {
                return BikeResult.error("0", "车辆异常，请更换车桩", null);
            }
        }



        return BikeResult.ok("1", "校验通过", null);
    }
}
